<template>
  <div class="user-container">
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="search.username" placeholder="用户名" clearable @keyup.enter="searchUser">
            <template #append>
              <el-button @click="searchUser">搜索</el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select v-model="search.status" placeholder="用户状态">
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="search.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-col>
        <el-col :span="6" style="text-align: right">
          <el-button type="primary" @click="addUser">
            <el-icon><Plus /></el-icon>新增用户
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="table-card">
      <el-table
        :data="userList"
        stripe
        border
        fit
        highlight-current-row
        @row-dblclick="editUser">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleStatusChange(scope.row.id, scope.row.status)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="primary" @click="editUser(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        style="margin-top: 20px; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total">
      </el-pagination>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="用户管理">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" active-value="1" inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="formData.roleId" placeholder="请选择角色">
            <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认删除对话框 -->
    <el-dialog :visible.sync="deleteDialogVisible" title="提示">
      <template #content>
        <p>确定要删除该用户吗？</p>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUsers, addUser, updateUser, deleteUser as apiDeleteUser, getRoles } from '@/api/user'

const router = useRouter()

// 搜索条件
const search = reactive({
  username: '',
  status: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 用户列表
const userList = ref([])

// 角色列表
const roleList = ref([])

// 对话框状态
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const formRef = ref(null)
const formData = reactive({
  id: null,
  username: '',
  name: '',
  password: '',
  email: '',
  phone: '',
  status: '1',
  roleId: ''
})

// 表单验证规则
const formRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur', validator: (rule, value, callback) => {
        if (!formData.id && !value) {
          callback(new Error('请输入密码'))
        } else {
          callback()
        }
      }
    },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
})

// 当前要删除的用户ID
const currentDeleteId = ref(null)

// 获取用户列表
const fetchUserList = async () => {
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      username: search.username,
      status: search.status,
      startTime: search.dateRange?.[0] || '',
      endTime: search.dateRange?.[1] || ''
    }

    const res = await getUsers(params)
    userList.value = res.data.list
    pagination.total = res.data.total
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const res = await getRoles()
    roleList.value = res.data
  } catch (error) {
    console.error('获取角色列表失败', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 搜索用户
const searchUser = () => {
  pagination.currentPage = 1
  fetchUserList()
}

// 分页相关方法
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchUserList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchUserList()
}

// 新增用户
const addUser = () => {
  formData.id = null
  formData.username = ''
  formData.name = ''
  formData.password = ''
  formData.email = ''
  formData.phone = ''
  formData.status = '1'
  formData.roleId = ''

  dialogVisible.value = true

  nextTick(() => {
    formRef.value.resetFields()
  })
}

// 编辑用户
const editUser = (row) => {
  formData.id = row.id
  formData.username = row.username
  formData.name = row.name
  formData.password = ''
  formData.email = row.email
  formData.phone = row.phone
  formData.status = row.status.toString()
  formData.roleId = row.roleId

  dialogVisible.value = true

  nextTick(() => {
    formRef.value.resetFields()
  })
}

// 保存用户
const saveUser = () => {
  formRef.value.validate(valid => {
    if (valid) {
      const params = { ...formData }

      if (formData.id) {
        // 更新用户
        updateUser(params).then(() => {
          ElMessage.success('更新用户成功')
          dialogVisible.value = false
          fetchUserList()
        }).catch(error => {
          console.error('更新用户失败', error)
          ElMessage.error('更新用户失败')
        })
      } else {
        // 新增用户
        addUser(params).then(() => {
          ElMessage.success('新增用户成功')
          dialogVisible.value = false
          fetchUserList()
        }).catch(error => {
          console.error('新增用户失败', error)
          ElMessage.error('新增用户失败')
        })
      }
    } else {
      console.log('验证失败')
      return false
    }
  })
}

// 删除用户
const deleteUser = (id) => {
  currentDeleteId.value = id
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = () => {
  apiDeleteUser(currentDeleteId.value).then(() => {
    ElMessage.success('删除用户成功')
    deleteDialogVisible.value = false
    fetchUserList()
  }).catch(error => {
    console.error('删除用户失败', error)
    ElMessage.error('删除用户失败')
  })
}

// 处理用户状态变更
const handleStatusChange = (id, status) => {
  ElMessageBox.confirm(
    `确定要${status ? '启用' : '禁用'}该用户吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    updateUser({ id, status: status ? 1 : 0 }).then(() => {
      ElMessage.success('更新用户状态成功')
    }).catch(() => {
      // 回滚状态
      const user = userList.value.find(item => item.id === id)
      if (user) {
        user.status = !status
      }
    })
  }).catch(() => {
    // 回滚状态
    const user = userList.value.find(item => item.id === id)
    if (user) {
      user.status = !status
    }
  })
}

onMounted(() => {
  fetchUserList()
  fetchRoleList()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  min-height: 400px;
}
</style>
